import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';

const fs = require('fs');

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    let message = exception.message;
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    // 错误时间
    let date = new Date();
    let err_time = `${date.getFullYear()}/${
      date.getMonth() + 1
    }/${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()} `;
    let writeFileMessage = err_time + '\n' + message + '\n';
    // 将错误信息写入log文件中 开发环境
    fs.appendFile('../err.log', writeFileMessage, (err) => {
      // 生产环境 因为生产环境启动是在dist文件夹下，所以需要再上一层目录
      // fs.appendFile('../../err.log', writeFileMessage, (err) => {
      if (err) {
        Logger.log(err);
        message = err;
      }
    });

    response.status(status).json({
      code: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: message,
      data: [],
    });
  }
}
